<template>
  <div class="ticketDetail">
    <div class="item_box">
      <p class="item_title">单据信息</p>
      <p class="item" v-for="item in ticketList" :key="item.id">
        <span class="item_left">{{ item.name }}</span>

        <span class="item_right" v-if="item.val == 'exceptionTypeNameList'">{{
          (dataDetail.exceptionTypeNameList &&
            dataDetail.exceptionTypeNameList.join(',')) ||
          '-'
        }}</span>

        <span class="item_right" v-else-if="item.val == 'urgencyLevel'">
          <van-tag
            plain
            :type="['primary', 'danger', 'warning'][dataDetail[item.val]] || ''"
            >{{ urgencyLevelList[dataDetail[item.val]] || '-' }}</van-tag
          >
        </span>
        <span class="item_right" v-else-if="item.val == 'timeLimit'"
          >{{ dataDetail.timeLimit || 0 }} 小时</span
        >
        <span class="item_right" v-else>{{ dataDetail[item.val] || '-' }}</span>
      </p>

      <div>
        <div>
          <p class="upload_img upload_img1">
            <span class="bt">*</span> <span>情况描述</span>
          </p>
          <div class="remark">
            {{ dataDetail.remark }}
          </div>
        </div>
        <div>
          <div class="upload_img upload_img1">
            <p><span class="bt">*</span> <span>现场图片</span></p>
            <van-uploader
              class="custom_uploader"
              v-model="fileList"
              :after-read="afterRead"
              @delete="handleDeleteFile"
              :deletable="true"
              :disabled="form.photoIdList.length >= 3"
              input-accept="image/*"
            />
          </div>
          <div>
            <template v-if="dataDetail.fileVOList">
              <van-image
                class="item_img"
                :src="src"
                alt=""
                :key="src"
                v-for="src in dataDetail.fileVOList"
              >
                <template v-slot:loading>
                  <van-loading type="spinner" size="20" />
                </template>
              </van-image>
            </template>
            <van-form @failed="onFailed" @submit="onSubmit">
              <van-cell-group>
                <!-- <van-field
                  v-model="form.duration"
                  required
                  name="picker"
                  label="维修时长"
                  placeholder="维修时长"
                  :rules="[{ required: true, message: '维修时长' }]"
                /> -->
                <div>
                  <p class="upload_img">
                    <span class="bt">*</span> <span>维修时长</span>
                  </p>
                  <div class="time_box">
                    <div>
                      <van-button @click="handleMinus" icon="minus" plain size="small" />
                      <p class="val">{{ form.duration }}</p>
                      <van-button @click="handlePlus" icon="plus" plain size="small" />
                    </div>
                    小时
                  </div>
                </div>
                <van-field
                  is-link
                  required
                  readonly
                  v-model="partUseParamList"
                  type="text"
                  name="备件消耗"
                  label="备件消耗"
                  placeholder="备件消耗"
                  :rules="[{ required: true, message: '备件消耗' }]"
                  @click="handleSelect('partUseParamList')"
                />
                <van-popup v-model:show="showPicker" position="bottom">
                  <van-picker
                    :columns="partOptions"
                    @confirm="onConfirm"
                    @cancel="showPicker = false"
                  />
                </van-popup>
                <van-field
                  required
                  v-model="form.content"
                  type="text"
                  name="处理内容"
                  label="处理内容"
                  placeholder="处理内容"
                  :rules="[{ required: true, message: '处理内容' }]"
                />
              </van-cell-group>
              <div class="btns">
                <van-button block type="primary" native-type="submit"> 提交 </van-button>
              </div>
            </van-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { showNotify } from 'vant';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
import { fillInOrder, getOrderInfo } from '@/api/workOrder.js';
import { fileUpload } from '@/api/common.js';
import { getPartAll } from '@/api/equipmentLedger.js';
const urgencyLevelList = ['一般', '严重', '紧急'];
const fileList = ref([]);
const fileIds = ref([]);
const form = reactive({
  id: route.params.id,
  duration: 0,
  partUseParamList: [],
  photoIdList: [],
  content: '',
});
const partUseParamList = ref('');
const showPicker = ref(false);
const selectKey = ref('');
const partOptions = ref([]);

const dataDetail = ref({});
const ticketList = [
  {
    val: 'number',
    name: '工单编号',
  },
  {
    val: 'deviceName',
    name: '异常设备',
  },
  {
    val: 'installLocation',
    name: '安装位置',
  },
  {
    val: 'exceptionTypeNameList',
    name: '异常类型',
  },
  {
    val: 'item',
    name: '异常项目',
  },
  {
    val: 'reporteName',
    name: '上报人员',
  },
  {
    val: 'dispatchUserName',
    name: '派工人员',
  },
  {
    val: 'urgencyLevel',
    name: '紧急程度',
  },
  {
    val: 'timeLimit',
    name: '处理时效',
  },
];

onMounted(async () => {
  if (route.params.id) {
    await getInfo(route.params.id);
    await getParts();
  }
});

async function getInfo(id) {
  await getOrderInfo(id)
    .then((res) => {
      if (res.code == 200) {
        console.log('res', res);
        dataDetail.value = res.data;
      }
    })
    .catch((err) => {
      console.log('err', err);
    })
    .finally(() => {});
}

const getParts = async (file) => {
  const res = await getPartAll()
    .catch((err) => {
      console.log('err', err);
    })
    .finally(() => {});
  partOptions.value =
    (res.data &&
      res.data.map((v) => {
        v.text = v.name;
        v.value = v.id;
        return v;
      })) ||
    [];
};
const handleDeleteFile = (file) => {
  const index = fileIds.value.indexOf(file.file.lastModified);
  form.photoIdList.splice(index, 1);
  fileIds.value = fileIds.value.filter((v) => {
    return v !== file.file.lastModified;
  });
};
const afterRead = (file) => {
  file.status = 'uploading';
  file.message = '上传中...';
  uploadFile(file);
};

const uploadFile = (file) => {
  const formData = new FormData();
  formData.append('file', file.file);
  fileUpload(formData)
    .then((res) => {
      if (res.code == 200) {
        showNotify({ type: 'success', message: '成功！' });
        form.photoIdList.push(res.data.id);
        fileIds.value.push(file.file.lastModified);
      } else {
        showNotify({ type: 'warning', message: '异常！' });
      }
    })
    .catch((error) => {
      console.error(error);
      showNotify({ type: 'error', message: '失败！' });
    })
    .finally(() => {
      file.status = 'done';
      file.message = '';
    });
};

const onSubmit = (values) => {
  const partUseParamList = [];
  partOptions.value.length > 0 &&
    partOptions.value.forEach((v) => {
      if (form.partUseParamList == v.id) {
        partUseParamList.push({
          id: v.id,
          num: v.quantity,
        });
      }
    });
  const params = {
    partUseParamList,
    id: form.id,
    duration: form.duration,
    photoIdList: form.photoIdList ?? [],
    content: form.content,
  };

  fillInOrder(params)
    .then((res) => {
      if (res.code == 200) {
        showNotify({ type: 'success', message: '成功' });
        setTimeout(router.push({ path: '/ticket' }), 1000);
      }
    })
    .catch((err) => {
      showNotify({ type: 'warning', message: err.msg || '异常' });
    })
    .finally(() => {});
};
const onFailed = (errorInfo) => {
  console.log('failed', errorInfo);
};
const onConfirm = ({ selectedOptions }) => {
  partUseParamList.value = selectedOptions[0]?.text;
  form.partUseParamList = selectedOptions[0]?.value;
  showPicker.value = false;
};
const handleSelect = (key) => {
  showPicker.value = true;
  selectKey.value = key;
};

const handleMinus = (errorInfo) => {
  if (form.duration > 0) {
    form.duration--;
  }
};
const handlePlus = (errorInfo) => {
  form.duration++;
};
</script>

<style scoped lang="scss">
.ticketDetail {
  padding: 0 0 48px 0;
  width: 100%;
  height: calc(100vh - 80px);
  overflow-y: hidden;
  .item_box {
    height: 100%;
    overflow-y: auto;
    padding: 0 16px;
  }
  .item {
    display: flex;
    justify-content: space-between;
    padding-left: 16px;
  }
  .item_title {
    height: 24px;
    font-weight: bold;
    font-size: 15px;
    color: #333333;
    line-height: 24px;
    margin-top: 20px;
    padding-left: 16px;
  }
  .item_left {
    height: 36px;
    line-height: 36px;
  }
  .item_right {
    width: 50%;
    height: 36px;
    line-height: 36px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #666666;
  }

  .upload_img1 {
    // padding: 0;
    margin-top: 10px;
  }
  .remark {
    padding: 10px;
    box-sizing: border-box;
    width: 100%;
    min-height: 80px;
    background: #f8f8f8;
    border-radius: 2px 2px 2px 2px;
  }
  .item_img {
    width: 75px;
    height: 75px;
    margin: 0 5.5px;
  }

  .time_box {
    padding-left: 36px;
    display: flex;
    justify-content: start;
    align-items: center;
    gap: 24px 0;
    margin-bottom: 12px;
  }
  .time_box > div {
    margin: 0 24px;
    width: 120px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
